from flask import Blueprint, jsonify, request
from datetime import datetime, timedelta
import logging

logger = logging.getLogger(__name__)

statistics_bp = Blueprint('statistics', __name__, url_prefix='/api/statistics')


@statistics_bp.route('/device', methods=['GET'])
def get_device_statistics():
    """
    获取设备使用统计
    返回所有设备的使用次数和使用量统计
    """
    try:
        # 固定数据示例
        device_stats = [
            {
                'device_id': 'VENT001',
                'device_name': '呼吸机-001',
                'ward': 'ICU-1',
                'bed': '1号床',
                'usage_count': 156,  # 使用次数
                'usage_volume': 2340.5,  # 使用量（L）
                'last_used': (datetime.now() - timedelta(hours=2)).isoformat(),
                'avg_volume_per_use': 15.0  # 平均每次使用量
            },
            {
                'device_id': 'VENT002',
                'device_name': '呼吸机-002',
                'ward': 'ICU-1',
                'bed': '2号床',
                'usage_count': 203,
                'usage_volume': 3145.2,
                'last_used': (datetime.now() - timedelta(hours=1)).isoformat(),
                'avg_volume_per_use': 15.5
            },
            {
                'device_id': 'VENT003',
                'device_name': '呼吸机-003',
                'ward': 'ICU-2',
                'bed': '1号床',
                'usage_count': 89,
                'usage_volume': 1423.8,
                'last_used': (datetime.now() - timedelta(hours=5)).isoformat(),
                'avg_volume_per_use': 16.0
            },
            {
                'device_id': 'VENT004',
                'device_name': '呼吸机-004',
                'ward': 'ICU-2',
                'bed': '3号床',
                'usage_count': 178,
                'usage_volume': 2667.4,
                'last_used': (datetime.now() - timedelta(minutes=30)).isoformat(),
                'avg_volume_per_use': 15.0
            },
            {
                'device_id': 'VENT005',
                'device_name': '呼吸机-005',
                'ward': 'ICU-3',
                'bed': '2号床',
                'usage_count': 134,
                'usage_volume': 2010.5,
                'last_used': (datetime.now() - timedelta(hours=3)).isoformat(),
                'avg_volume_per_use': 15.0
            }
        ]
        
        # 计算汇总数据
        summary = {
            'total_devices': len(device_stats),
            'total_usage_count': sum(d['usage_count'] for d in device_stats),
            'total_usage_volume': round(sum(d['usage_volume'] for d in device_stats), 2),
            'avg_usage_count': round(sum(d['usage_count'] for d in device_stats) / len(device_stats), 2),
            'avg_usage_volume': round(sum(d['usage_volume'] for d in device_stats) / len(device_stats), 2)
        }
        
        return jsonify({
            'code': 200,
            'message': '获取设备统计成功',
            'data': {
                'summary': summary,
                'devices': device_stats
            }
        })
    except Exception as e:
        logger.error(f"获取设备统计失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'获取设备统计失败: {str(e)}'
        }), 500


@statistics_bp.route('/bed', methods=['GET'])
def get_bed_statistics():
    """
    获取病床使用统计
    按病床统计使用次数和使用量
    """
    try:
        # 固定数据示例
        bed_stats = [
            {
                'ward': 'ICU-1',
                'bed': '1号床',
                'device_id': 'VENT001',
                'device_name': '呼吸机-001',
                'usage_count': 156,
                'usage_volume': 2340.5,
                'patient_name': '张三',
                'admission_date': (datetime.now() - timedelta(days=7)).isoformat(),
                'total_days': 7
            },
            {
                'ward': 'ICU-1',
                'bed': '2号床',
                'device_id': 'VENT002',
                'device_name': '呼吸机-002',
                'usage_count': 203,
                'usage_volume': 3145.2,
                'patient_name': '李四',
                'admission_date': (datetime.now() - timedelta(days=10)).isoformat(),
                'total_days': 10
            },
            {
                'ward': 'ICU-1',
                'bed': '3号床',
                'device_id': None,
                'device_name': '未分配',
                'usage_count': 0,
                'usage_volume': 0,
                'patient_name': None,
                'admission_date': None,
                'total_days': 0
            },
            {
                'ward': 'ICU-2',
                'bed': '1号床',
                'device_id': 'VENT003',
                'device_name': '呼吸机-003',
                'usage_count': 89,
                'usage_volume': 1423.8,
                'patient_name': '王五',
                'admission_date': (datetime.now() - timedelta(days=5)).isoformat(),
                'total_days': 5
            },
            {
                'ward': 'ICU-2',
                'bed': '2号床',
                'device_id': None,
                'device_name': '未分配',
                'usage_count': 0,
                'usage_volume': 0,
                'patient_name': None,
                'admission_date': None,
                'total_days': 0
            },
            {
                'ward': 'ICU-2',
                'bed': '3号床',
                'device_id': 'VENT004',
                'device_name': '呼吸机-004',
                'usage_count': 178,
                'usage_volume': 2667.4,
                'patient_name': '赵六',
                'admission_date': (datetime.now() - timedelta(days=8)).isoformat(),
                'total_days': 8
            },
            {
                'ward': 'ICU-3',
                'bed': '1号床',
                'device_id': None,
                'device_name': '未分配',
                'usage_count': 0,
                'usage_volume': 0,
                'patient_name': None,
                'admission_date': None,
                'total_days': 0
            },
            {
                'ward': 'ICU-3',
                'bed': '2号床',
                'device_id': 'VENT005',
                'device_name': '呼吸机-005',
                'usage_count': 134,
                'usage_volume': 2010.5,
                'patient_name': '孙七',
                'admission_date': (datetime.now() - timedelta(days=6)).isoformat(),
                'total_days': 6
            }
        ]
        
        # 按病房分组统计
        ward_groups = {}
        for bed in bed_stats:
            ward = bed['ward']
            if ward not in ward_groups:
                ward_groups[ward] = {
                    'ward': ward,
                    'total_beds': 0,
                    'occupied_beds': 0,
                    'total_usage_count': 0,
                    'total_usage_volume': 0,
                    'beds': []
                }
            ward_groups[ward]['total_beds'] += 1
            if bed['device_id']:
                ward_groups[ward]['occupied_beds'] += 1
            ward_groups[ward]['total_usage_count'] += bed['usage_count']
            ward_groups[ward]['total_usage_volume'] += bed['usage_volume']
            ward_groups[ward]['beds'].append(bed)
        
        # 转换为列表并计算百分比
        ward_list = []
        for ward_data in ward_groups.values():
            ward_data['total_usage_volume'] = round(ward_data['total_usage_volume'], 2)
            ward_data['occupancy_rate'] = round(
                (ward_data['occupied_beds'] / ward_data['total_beds'] * 100) if ward_data['total_beds'] > 0 else 0,
                2
            )
            ward_list.append(ward_data)
        
        # 计算汇总数据
        summary = {
            'total_beds': len(bed_stats),
            'occupied_beds': sum(1 for b in bed_stats if b['device_id']),
            'total_usage_count': sum(b['usage_count'] for b in bed_stats),
            'total_usage_volume': round(sum(b['usage_volume'] for b in bed_stats), 2),
            'occupancy_rate': round(
                (sum(1 for b in bed_stats if b['device_id']) / len(bed_stats) * 100) if len(bed_stats) > 0 else 0,
                2
            )
        }
        
        return jsonify({
            'code': 200,
            'message': '获取病床统计成功',
            'data': {
                'summary': summary,
                'wards': ward_list,
                'beds': bed_stats
            }
        })
    except Exception as e:
        logger.error(f"获取病床统计失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'获取病床统计失败: {str(e)}'
        }), 500


@statistics_bp.route('/trend', methods=['GET'])
def get_usage_trend():
    """
    获取使用趋势数据
    返回最近7天的使用统计
    """
    try:
        # 生成最近7天的数据
        trend_data = []
        for i in range(6, -1, -1):
            date = datetime.now() - timedelta(days=i)
            trend_data.append({
                'date': date.strftime('%Y-%m-%d'),
                'usage_count': 120 + (i * 15) + (i % 3) * 10,  # 模拟波动
                'usage_volume': round(1800 + (i * 200) + (i % 3) * 150, 2),
                'active_devices': 4 + (i % 2)
            })
        
        return jsonify({
            'code': 200,
            'message': '获取使用趋势成功',
            'data': trend_data
        })
    except Exception as e:
        logger.error(f"获取使用趋势失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'获取使用趋势失败: {str(e)}'
        }), 500

